package com.sunshine.wrongquestionset.activity.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider

import com.google.android.material.appbar.MaterialToolbar

import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.callback.OnRefreshListener
import com.sunshine.wrongquestionset.room.entity.AppConfigEntity
import es.dmoral.toasty.Toasty

import kotlinx.android.synthetic.main.activity_base.view.*

/**
 * @author sunshine
 * @date 2021/3/27
 * 活动基类
 */
open class BaseActivity : AppCompatActivity() {

    private lateinit var baseView: View
    //设置是否显示左上角返回键，默认显示
    private var enableDisplayHomeAsUp = true

    private lateinit var viewModel: BaseViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        baseView = LayoutInflater.from(this).inflate(R.layout.activity_base, null, false)

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(BaseViewModel::class.java)

        //如果用户配置为空，则进行获取
        if (loginUserAppConfig == null) {
            updateAppConfig()
        }

        activityList.add(this)
    }

    override fun setContentView(layoutResID: Int) {
        val view = LayoutInflater.from(this).inflate(layoutResID, baseView.container, false)
        baseView.container.addView(view)

        window.setContentView(baseView)
        setSupportActionBar(baseView.toolbar)

        //显示返回键
        if (enableDisplayHomeAsUp) {
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
            supportActionBar?.setHomeButtonEnabled(true)
        }
    }

    /**
     * 设置不带返回键的ActionBar
     */
    fun setContentViewWithoutDisplayHomeAsUp(layoutResID: Int) {
        this.enableDisplayHomeAsUp = false
        setContentView(layoutResID)
    }

    fun setTitle(title: String) {
        supportActionBar?.title = title
    }

    fun setActionBarVisibility(boolean: Boolean) {
        baseView.appBarLayout.visibility = if (boolean) View.VISIBLE else View.GONE
    }

    fun getToolbar(): MaterialToolbar? {
        return baseView.toolbar
    }

    /**
     * 刷新用户配置
     */
    private fun updateAppConfig() {
        updateAppConfig(null)
    }

    /**
     * 带回调的刷新用户配置
     */
    fun updateAppConfig(callback: OnRefreshListener<AppConfigEntity>?) {
        viewModel.getLoginUser().observe(this, Observer {
            if (it == null) return@Observer
            viewModel.getLoginUserAppConfig(it).observe(this, Observer {appConfigEntity->
                loginUserAppConfig = appConfigEntity
                loginUserId = appConfigEntity.id

                callback?.onUpdate(appConfigEntity)
            })
        })
    }

    @Deprecated("采用了带回调式，更安全", ReplaceWith(""))
    fun getLoginUserAppConfig(): AppConfigEntity? {
        return loginUserAppConfig
    }

    fun getLoginUserAppConfig(callback: OnRefreshListener<AppConfigEntity>) {
        if (loginUserAppConfig == null) {
            updateAppConfig(object : OnRefreshListener<AppConfigEntity>() {
                override fun onUpdate(obj: AppConfigEntity) {
                    super.onUpdate(obj)
                    callback.onUpdate(obj)
                    callback.onUpdate()
                }
            })
        } else {
            callback.onUpdate(loginUserAppConfig!!)
            callback.onUpdate()
        }
    }

    @Deprecated("建议采用带回调式，使得获取的数据更加安全", ReplaceWith("getLoginUserId(callback: OnRefreshListener<String>)"))
    fun getLoginUserId(): String {
        return loginUserId?:""
    }

    /**
     * 带回调的获取用户Id
     */
    fun getLoginUserId(callback: OnRefreshListener<String>) {
        if (loginUserId.isNullOrBlank()) {
            updateAppConfig(object : OnRefreshListener<AppConfigEntity>() {
                override fun onUpdate(obj: AppConfigEntity) {
                    super.onUpdate(obj)
                    callback.onUpdate(obj.id)
                    callback.onUpdate()
                }
            })
        }
        else {
            callback.onUpdate(loginUserId!!)
            callback.onUpdate()
        }
    }

    /**
     * 结束所有该基类的子类活动
     */
    fun finishAll() {
        activityList.forEach {
            it.finish()
        }
    }

    /**
     * 结束除调用者外所有活动
     */
    fun finishAllWithoutThis(thisActivity: BaseActivity) {
        activityList.forEach {
            if (thisActivity != it) {
                it.finish()
            }
        }
    }

    fun clearAppConfig() {
        loginUserAppConfig = null
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            android.R.id.home -> {
                finish()
                false
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        activityList.remove(this)
    }

    companion object {
        //登录的用户配置
        private var loginUserAppConfig: AppConfigEntity? = null
        private var loginUserId: String? = null

        //所有活动的列表，用于管理活动，在活动创建时添加，在销毁时移除
        private val activityList = ArrayList<BaseActivity>()
    }
}